package com.demo.controller;

import com.demo.pojo.User;
import com.demo.service.UserService;
import com.myspringmvc.annotation.Autowired;
import com.myspringmvc.annotation.RequestMapping;
import com.myspringmvc.annotation.RequestParam;
import com.myspringmvc.annotation.bean.Controller;
import com.mytomcat.servlet.MyHttpServletResponse;

import java.util.List;


@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/user")
    public List<User> getUsers(@RequestParam("pageNum") String pageNum, @RequestParam("pageSize") String pageSize) {
        int pageNumInt = 1;
        int pageSizeInt = 10;
        if (pageNum != null && pageNum.matches("\\d+"))
            pageNumInt = Integer.parseInt(pageNum);
        if (pageNum != null && pageNum.matches("\\d+"))
            pageSizeInt = Integer.parseInt(pageSize);
        return userService.getUsers(pageNumInt, pageSizeInt);
    }

    /**
     * 手动生成html页面并返回
     *
     * @param response
     * @throws Exception
     */
    @RequestMapping("/view/user")
    public void getUsersOfView(MyHttpServletResponse response) throws Exception {
        List<User> list = userService.getUsers(1, 10);
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("<html>")
                .append("<head>" +
                        "   <meta charset='UTF-8'>" +
                        "   <style type='text/css'>" +
                        "        body{" +
                        "            background:lightskyblue;" +
                        "            text-align:center;" +
                        "        }" +
                        "        table{ margin:0 auto; width:75%; border-collapse:collapse;}" +
                        "        table tr{ background:aliceblue;}" +
                        "        table tr:first-child{ background:DarkGray;}" +
                        "    </style></head>")
                .append("<body>")
                .append("<table border='1'>");
        stringBuilder
                .append("<tr>")
                .append("<th>用户名</th>")
                .append("<th>密码</th>")
                .append("</tr>");
        for (User user : list) {
            stringBuilder
                    .append("<tr>")
                    .append("<td>").append(user.username).append("</td>")
                    .append("<td>").append(user.username).append("</td>")
                    .append("</tr>");
        }
        stringBuilder.append("</table></body></html>");
        response.returnHtmlResponse(200, stringBuilder.toString());
    }
}
